// pages/video-history/video-history.js
const apiConfig = require('../../config/api-config.js')

Page({
  data: {
    videoHistory: [],
    totalWatchTime: 0, // 总观看时长（分钟）
    isEmpty: false,
    userId: 1 // 默认用户ID，实际应从登录状态获取
  },

  onLoad() {
    // 尝试从本地存储获取用户ID
    const userInfo = wx.getStorageSync('userInfo')
    if (userInfo && userInfo.id) {
      this.setData({ userId: userInfo.id })
    }
    this.loadVideoHistory()
  },

  onShow() {
    this.loadVideoHistory()
  },

  // 加载视频播放记录
  loadVideoHistory() {
    const that = this
    
    // 显示加载提示
    wx.showLoading({
      title: '加载中...',
      mask: true
    })

    // 从后端API获取播放记录
    wx.request({
      url: `${apiConfig.other.backendUrl}/playRecord/list`,
      method: 'GET',
      data: {
        userId: this.data.userId
      },
      success: (res) => {
        console.log('播放记录API返回:', res.data)
        
        if (res.data.code === 200 && res.data.data) {
          const recordList = res.data.data
          
          // 转换API数据格式为页面需要的格式
          const formattedHistory = recordList.map(record => {
            const chapter = record.chapter || {}
            const content = record.content || {}
            
            // 计算播放进度百分比
            const duration = chapter.duration || 0 // 章节总时长（秒）
            const progress = record.progress || 0 // 已播放时长（秒）
            const progressPercent = duration > 0 ? Math.round((progress / duration) * 100) : 0
            
            return {
              id: record.id,
              courseId: record.contentId,
              chapterId: record.chapterId,
              title: content.title || '未知课程',
              cover: content.cover || '/images/courses/course1.svg',
              duration: Math.round(duration / 60), // 转换为分钟
              watchedTime: Math.round(progress / 60), // 转换为分钟
              progress: progressPercent,
              lastWatchTime: that.formatTime(record.lastPlayTime),
              chapterTitle: chapter.title || '未知章节'
            }
          })
          
          that.setData({
            videoHistory: formattedHistory,
            isEmpty: formattedHistory.length === 0,
            totalWatchTime: that.calculateTotalTime(formattedHistory)
          })
        } else {
          // 如果没有数据，显示空状态
          that.setData({
            videoHistory: [],
            isEmpty: true,
            totalWatchTime: 0
          })
        }
      },
      fail: (err) => {
        console.error('获取播放记录失败:', err)
        
        // API调用失败，使用模拟数据
        const mockHistory = that.getMockHistory()
        that.setData({
          videoHistory: mockHistory,
          isEmpty: mockHistory.length === 0,
          totalWatchTime: that.calculateTotalTime(mockHistory)
        })
        
        wx.showToast({
          title: '加载失败，使用本地数据',
          icon: 'none'
        })
      },
      complete: () => {
        wx.hideLoading()
      }
    })
  },

  // 格式化时间
  formatTime(dateString) {
    if (!dateString) return ''
    
    const date = new Date(dateString)
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hour = String(date.getHours()).padStart(2, '0')
    const minute = String(date.getMinutes()).padStart(2, '0')
    
    return `${year}-${month}-${day} ${hour}:${minute}`
  },

  // 获取模拟播放记录
  getMockHistory() {
    return [
      {
        id: 1,
        courseId: 1,
        title: '中医基础理论',
        cover: '/images/courses/course1.svg',
        duration: 120, // 视频总时长（分钟）
        watchedTime: 45, // 已观看时长（分钟）
        progress: 37.5, // 播放进度（百分比）
        lastWatchTime: '2024-01-10 14:30',
        chapterTitle: '第一章：阴阳五行'
      },
      {
        id: 2,
        courseId: 2,
        title: '穴位按摩手法',
        cover: '/images/courses/course2.svg',
        duration: 90,
        watchedTime: 78,
        progress: 86.7,
        lastWatchTime: '2024-01-10 10:20',
        chapterTitle: '第三章：常用穴位按摩'
      },
      {
        id: 3,
        courseId: 4,
        title: '艾灸基础入门',
        cover: '/images/courses/course1.svg',
        duration: 60,
        watchedTime: 15,
        progress: 25,
        lastWatchTime: '2024-01-09 16:45',
        chapterTitle: '第一章：艾灸工具介绍'
      },
      {
        id: 4,
        courseId: 7,
        title: '经络穴位详解',
        cover: '/images/courses/course1.svg',
        duration: 180,
        watchedTime: 135,
        progress: 75,
        lastWatchTime: '2024-01-09 09:15',
        chapterTitle: '第五章：十二经脉'
      },
      {
        id: 5,
        courseId: 8,
        title: '小儿推拿入门',
        cover: '/images/courses/course2.svg',
        duration: 120,
        watchedTime: 12,
        progress: 10,
        lastWatchTime: '2024-01-08 20:30',
        chapterTitle: '第一章：小儿推拿概述'
      }
    ]
  },

  // 计算总观看时长
  calculateTotalTime(history) {
    return history.reduce((total, item) => total + item.watchedTime, 0)
  },

  // 格式化时长
  formatDuration(minutes) {
    const hours = Math.floor(minutes / 60)
    const mins = minutes % 60
    if (hours > 0) {
      return `${hours}小时${mins}分钟`
    }
    return `${mins}分钟`
  },

  // 继续播放
  onContinuePlay(e) {
    const { id, courseId } = e.currentTarget.dataset
    console.log('继续播放课程:', courseId)
    
    wx.navigateTo({
      url: `/pages/course-detail/course-detail?id=${courseId}`
    })
  },

  // 删除单条记录
  onDeleteItem(e) {
    const { id } = e.currentTarget.dataset
    const that = this
    
    // 找到要删除的记录
    const record = this.data.videoHistory.find(item => item.id === id)
    if (!record) return
    
    wx.showModal({
      title: '确认删除',
      content: '确定要删除这条播放记录吗？',
      success: (res) => {
        if (res.confirm) {
          // 使用 URL 参数方式发送 DELETE 请求
          const params = `userId=${that.data.userId}&contentId=${record.courseId}`
          
          wx.request({
            url: `${apiConfig.other.backendUrl}/playRecord/delete?${params}`,
            method: 'DELETE',
            header: {
              'content-type': 'application/x-www-form-urlencoded'
            },
            success: (res) => {
              if (res.data && res.data.code === 200) {
                // 删除成功，更新本地数据
                const newHistory = that.data.videoHistory.filter(item => item.id !== id)
                
                that.setData({
                  videoHistory: newHistory,
                  isEmpty: newHistory.length === 0,
                  totalWatchTime: that.calculateTotalTime(newHistory)
                })
                
                wx.showToast({
                  title: '已删除',
                  icon: 'success'
                })
              } else {
                wx.showToast({
                  title: '删除失败',
                  icon: 'none'
                })
              }
            },
            fail: (err) => {
              console.error('删除播放记录失败:', err)
              wx.showToast({
                title: '删除失败',
                icon: 'none'
              })
            }
          })
        }
      }
    })
  },

  // 清空所有记录
  onClearAll() {
    const that = this
    
    if (this.data.videoHistory.length === 0) {
      wx.showToast({
        title: '暂无记录',
        icon: 'none'
      })
      return
    }

    wx.showModal({
      title: '确认清空',
      content: '确定要清空所有播放记录吗？',
      success: (res) => {
        if (res.confirm) {
          // 批量删除所有记录
          const deletePromises = that.data.videoHistory.map(record => {
            return new Promise((resolve) => {
              const params = `userId=${that.data.userId}&contentId=${record.courseId}`
              
              wx.request({
                url: `${apiConfig.other.backendUrl}/playRecord/delete?${params}`,
                method: 'DELETE',
                header: {
                  'content-type': 'application/x-www-form-urlencoded'
                },
                success: () => resolve(true),
                fail: () => resolve(false)
              })
            })
          })
          
          // 等待所有删除操作完成
          Promise.all(deletePromises).then(() => {
            that.setData({
              videoHistory: [],
              isEmpty: true,
              totalWatchTime: 0
            })
            
            wx.showToast({
              title: '已清空',
              icon: 'success'
            })
          })
        }
      }
    })
  },

  // 返回上一页
  goBack() {
    if (getCurrentPages().length > 1) {
      wx.navigateBack()
    } else {
      wx.switchTab({ url: '/pages/index/index' })
    }
  }
})

